#encoding:utf8
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect,HttpResponse
from web.forms import *
import subprocess,sys,ConfigParser
sys.path.append('/cihi/app/include')
import init

k = init.INIT()
workdir = k.WorkDir

def home(request):    #首页展示页面
    status = {}
    status['okcount'] = len(k.getClientList('ok'))
    status['badcount'] = len(k.getClientList('bad'))
    return render_to_response('home.html',locals())
def nowtime(request):   #首页查看时间页面
    status = {}
    status['okcount'] = len(k.getClientList('ok'))
    status['badcount'] = len(k.getClientList('bad'))
    return render_to_response('time.html',locals())

def clientconf(request,param):  #主机配置  添加、编辑、删除  页面
    if param == 'del':
	k.delClient(request.GET.get('host'))
	return HttpResponseRedirect('/client/')
    elif param == 'edit':
        mode = '编辑'
        host = request.GET.get('host')
        default = k.getClientAtt(host)
        default['project'] = k.getClientHavProject(host)
        default['hostname'] = host
        default['password'] = ''
        default['username'] = ''
        default['port'] = ''
    else:
        mode = '添加'
        default = {}
    if request.method == 'POST':
        form = ClientForm(request.POST)
        if form.is_valid():
            error = ''
            result = form.cleaned_data
            host = result['hostname']
            if param == 'add':
                if host in k.getClientList():
                    error = u'该主机已存在。'
                else:
                    k.saveSSet('cihi_client',host)
            else:
                if host != request.GET.get('host'):error = u'不允许编辑IP地址。'
            if error:
                form.errors['hostname'] = [error]
            else:
                addproject = [ val for val in result['project'] if val not in default.get('project','') ]
                delproject = [ val for val in default.get('project','') if val not in result['project'] ]
                for project in addproject:
                    k.saveSet(project+'_hostlist',host)
                for project in delproject:
                    k.delSet(project+'_hostlist',host)
                del result['project']
                del result['hostname']
                if not result['password']:del result['password']
                if not result['username']:del result['username']
                if not result['port']:del result['port']
                k.saveHash(host+'_att',result)
                return HttpResponseRedirect('/client/')
    else:
        form = ClientForm(initial=default,label_suffix='')
    return render_to_response('addclient.html',locals())

def projectconf(request,param):  #项目配置 添加、编辑、删除  页面
    if param == 'del':
        k.delProject(request.GET.get('project'))
        return HttpResponseRedirect('/project')
    elif param == 'edit':
        project = request.GET.get('project')
        default = k.getProjectAtt(project)
        default['projectname'] = project
    else:
        default = {}
    if request.method == 'POST':
        form = ProjectForm(request.POST)
        if form.is_valid():
            error = ''
            result = form.cleaned_data 
            project = result['projectname']
            if param == 'add':
                if project in k.getProjectList():
                    error = u'该项目已存在。'
                else:
                    k.saveSSet('cihi_project',project)
            else:
                if project != request.GET.get('project'):error = u'不允许编辑项目代码。'
            if error:
                form.errors['projectname'] = [error]
            else:
                del result['projectname']
                k.saveHash(project+'_att',result)
                return HttpResponseRedirect('/project/')
    else:
        form = ProjectForm(initial=default,label_suffix='')
    return render_to_response('addproject.html',locals())

def clientlist(request):    #主机配置 页面
    result = []
    for host in k.getClientList():
        tmp = k.getClientAtt(host)
        tmp['hostname'] = host
        tmp['project'] = tmp['monitor'] = tmp['username'] = tmp['password'] = tmp['port'] = ''
        for project in k.getClientHavProject(host):
            tmp['project'] = tmp.get('project')+' '+k.getProjectAtt(project).get('projectalias')
        for monitor in k.getClientHavMonitor(host):
            tmp['monitor'] = tmp.get('monitor')+' '+k.getMonitorAtt(monitor).get('monitoralias')
        result.append(tmp)
    return render_to_response('host.html',locals())

def projectlist(request):   #项目配置 页面
    result = []
    for project in k.getProjectList():
        tmp = k.getProjectAtt(project)
        tmp['projectname'] = project
        result.append(tmp)
    return render_to_response('project.html',locals())
